package com.test45_JUC;

import java.util.concurrent.*;

/**
 * CompletionService，该接口可以将所有异步任务的执行结果保存到阻塞队列之中，
 * 而后再利用阻塞队列实现结果的获取
 */
public class Demo26_CompletionService {

    /**
     * 异步任务调度
     */
    public static void main(String[] args) throws Exception {
        ExecutorService service = Executors.newFixedThreadPool(2);  // 创建2个大小线程池
        // 现在的线程池统一被CompletionService实例所管理，所有线程任务交由此接口实例操作
        CompletionService<String> completionService = new ExecutorCompletionService<>(service);
        for (int x = 0; x < 5; x++) {
            completionService.submit(new TaskItem());   // 提交线程任务
        }
        for (int x = 0; x < 10; x++) {
            System.err.println(completionService.take().get());  // 获取执行结果
        }
        service.shutdown();  // 关闭线程池
    }
}

/**
 * 定义线程任务
 */
class TaskItem implements Callable<String> {

    @Override
    public String call() throws Exception {
        long start = System.currentTimeMillis();
        TimeUnit.SECONDS.sleep(1);
        long end = System.currentTimeMillis();
        return String.format("【%s】YOOTK任务执行完毕，任务的耗时时间为：%d",
                Thread.currentThread().getName(), (end - start));
    }
}
